#!/bin/bash

WORKSPACE=$(cd $(dirname $0)/; pwd)
cd $WORKSPACE

mkdir -p var
mkdir -p bin

module=cron
app=elves-$module
ver=$(ls -l bin | grep release | awk '{print $NF}' | awk -F '-' '{print $3}')
file=$(ls -l bin | grep release | awk '{print $NF}')
pidfile=./var/app.pid

function check_pid() {
    if [ -f $pidfile ];then
        pid=`cat $pidfile`
        if [ -n $pid ]; then
            running=`ps -p $pid|grep -v "PID TTY" |wc -l`
            return $running
        fi
    fi
    return 0
}

function start() {
    check_pid
    running=$?
    if [ $running -gt 0 ];then
        echo -n "$app now is running already, pid="
        cat $pidfile
        return 1
    fi
    cd $WORKSPACE/bin
    nohup java -jar ./$file $WORKSPACE >/dev/null 2>&1 &
    echo $! > .$pidfile
    echo "$app started..., pid=$!"
}

function stop() {
    pid=`cat $pidfile`
    kill $pid
    echo "$app stoped..."
}

function restart() {
    stop
    sleep 1
    start
}

function status() {
    check_pid
    running=$?
    if [ $running -gt 0 ];then
        echo started
    else
        echo stoped
    fi
}


function build() {
    mvn clean
    if [ $? -ne 0 ]; then
        exit $?
    fi
    mvn package
    if [ $? -ne 0 ]; then
        exit $?
    fi
}

function pack() {
    build
    FILENAME=$(ls -l bin | grep release | awk '{print $NF}')
    version=$(ls -l bin | grep release | awk '{print $NF}' | awk -F '-' '{print $3}')
    tar zcvf $app-linux-$version.tar.gz conf/ bin/$FILENAME control database.sql --exclude conf/conf.properties
}

function version() {
    echo $ver
}

function help() {
    echo "$0 build|pack|start|stop|restart|status|version"
}

if [ "$1" == "" ]; then
    help
elif [ "$1" == "stop" ];then
    stop
elif [ "$1" == "start" ];then
    start
elif [ "$1" == "restart" ];then
    restart
elif [ "$1" == "status" ];then
    status
elif [ "$1" == "build" ];then
    build
elif [ "$1" == "pack" ];then
    pack
elif [ "$1" == "version" ];then
    version
else
    help
fi
